﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.EmpbasicService;
using CommunitySystem.JuZhuanAnZhiService;
using CommunitySystem.PageView.EmpBasicManager;

namespace CommunitySystem
{
    public partial class JuZhuanAnZhiJiHuaEmpWindow : ChildWindow
    {
        private JuZhuanAnZhiService.JuZhuanAnZhiJiHuaEmpModel model =
            new JuZhuanAnZhiService.JuZhuanAnZhiJiHuaEmpModel();

        private JuZhuanAnZhiService.JuZhuanAnZhiServiceClient client =
            new JuZhuanAnZhiService.JuZhuanAnZhiServiceClient();

        private int ID;
        private int ExameID;
        private bool IsNew;
        private EmpbasicService.EmpBasicServiceClient empclient = new EmpbasicService.EmpBasicServiceClient();
        public ObservableCollection<BianZhiModel> BianZhiModels = new ObservableCollection<BianZhiModel>();
        public JuZhuanAnZhiJiHuaEmpWindow(int id, bool isnew,int exameID)
        {
            InitializeComponent();
            ID = id;
            ExameID = exameID;
            IsNew = isnew;
            
            if (IsNew)
            {
                model = new JuZhuanAnZhiJiHuaEmpModel();
                this.DataContext = model;
            }
            else
            {
                client.GetJuZhuanAnZhiJiHuaEmpModelCompleted +=
                    new EventHandler<GetJuZhuanAnZhiJiHuaEmpModelCompletedEventArgs>(client_GetJuZhuanAnZhiJiHuaEmpModelCompleted);
                client.GetJuZhuanAnZhiJiHuaEmpModelAsync(0, "", ID);
            }
            client.AddJuZhuanAnZhiJiHuaEmpModelCompleted +=
                new EventHandler<JuZhuanAnZhiService.AddJuZhuanAnZhiJiHuaEmpModelCompletedEventArgs>(client_AddJuZhuanAnZhiJiHuaEmpModelCompleted);
            client.UpdateJuZhuanAnZhiJiHuaEmpModelCompleted +=
                new EventHandler<JuZhuanAnZhiService.UpdateJuZhuanAnZhiJiHuaEmpModelCompletedEventArgs>(client_UpdateJuZhuanAnZhiJiHuaEmpModelCompleted);
            empclient.GetBianZhiDetailModelCompleted += new EventHandler<GetBianZhiDetailModelCompletedEventArgs>(Client2_GetBianZhiDetailModelCompleted);
        }

        void Client2_GetBianZhiDetailModelCompleted(object sender, GetBianZhiDetailModelCompletedEventArgs e)
        {
            BianZhiModels = e.Result;
            if (BianZhiModels != null && BianZhiModels.Count > 0)
            {
                string zhurenkeyong = "";
                int i1 =
                    Convert.ToInt32(
                        !string.IsNullOrEmpty(BianZhiModels.OrderBy(p => p.FuKeLingDao).FirstOrDefault().FuKeLingDao)
                            ? BianZhiModels.OrderBy(p => p.FuKeLingDao).FirstOrDefault().FuKeLingDao
                            : "0");
                int i2 =
                    Convert.ToInt32(
                        !string.IsNullOrEmpty(
                            BianZhiModels.OrderByDescending(p => p.zhurenshiyou).FirstOrDefault().zhurenshiyou)
                            ? BianZhiModels.OrderByDescending(p => p.zhurenshiyou).FirstOrDefault().zhurenshiyou
                            : "0");

                int i3 = 0;
                foreach (BianZhiModel b in BianZhiModels)
                {
                    if (!string.IsNullOrEmpty(b.ZhuRenJieYongQingKuang) && b.ZhuRenJieYongQingKuang != "无")
                    {
                        if (Math.Abs(Convert.ToInt32(b.ZhuRenJieYongQingKuang)) > i3)
                            i3 = Convert.ToInt32(b.ZhuRenJieYongQingKuang);
                    }
                }
                int i4 =
                    Convert.ToInt32(
                        BianZhiModels.OrderByDescending(p => p.ZhuRenChaoZhiQingKuang).FirstOrDefault().
                            ZhuRenChaoZhiQingKuang == "无"
                            ? "0"
                            : BianZhiModels.OrderByDescending(p => p.ZhuRenChaoZhiQingKuang).FirstOrDefault().
                                  ZhuRenChaoZhiQingKuang);
                zhurenkeyong = (i1 - i2 + i3 + i4).ToString();

                string fuzhurenkeyong = "";
                int f1 =
                    Convert.ToInt32(
                        !string.IsNullOrEmpty(BianZhiModels.OrderBy(p => p.FuKeFeiLingDao).FirstOrDefault().FuKeFeiLingDao)
                            ? BianZhiModels.OrderBy(p => p.FuKeFeiLingDao).FirstOrDefault().FuKeFeiLingDao
                            : "0");
                int f2 =
                    Convert.ToInt32(
                        !string.IsNullOrEmpty(
                            BianZhiModels.OrderByDescending(p => p.fuzhurenshiyou).FirstOrDefault().fuzhurenshiyou)
                            ? BianZhiModels.OrderByDescending(p => p.fuzhurenshiyou).FirstOrDefault().fuzhurenshiyou
                            : "0");

                int f3 = 0;
                foreach (BianZhiModel b in BianZhiModels)
                {
                    if (!string.IsNullOrEmpty(b.FuZhuRenJieYongQingKuang) && b.FuZhuRenJieYongQingKuang != "无")
                    {
                        if (Math.Abs(Convert.ToInt32(b.FuZhuRenJieYongQingKuang)) > f3)
                            f3 = Convert.ToInt32(b.FuZhuRenJieYongQingKuang);
                    }
                }
                int f4 =
                    Convert.ToInt32(
                        BianZhiModels.OrderByDescending(p => p.FuZhuRenChaoZhiQingKuang).FirstOrDefault().
                            FuZhuRenChaoZhiQingKuang == "无"
                            ? "0"
                            : BianZhiModels.OrderByDescending(p => p.FuZhuRenChaoZhiQingKuang).FirstOrDefault().
                                  FuZhuRenChaoZhiQingKuang);
                fuzhurenkeyong = (f1 - f2 + f3 + f4).ToString();
                if (BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Count() > 0)
                {
                    foreach (BianZhiModel i in BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true))
                    {
                        int zhiwhu = !string.IsNullOrEmpty(i.ZhengKeLingDao) ? Convert.ToInt32(i.ZhengKeLingDao) : 0;
                        int renshu = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                            p => !string.IsNullOrEmpty(p.zhengkeshiyou) ? Convert.ToInt32(p.zhengkeshiyou) : 0);
                        int jieyong = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                            p =>
                            p.ZhengKeJieYongQingKuang != "无" ? Convert.ToInt32(p.ZhengKeJieYongQingKuang) : 0);
                        int chaozhi = BianZhiModels.Where(p => p.ZhengKeLingDaoTC == true).Sum(
                            p =>
                            p.ZhengKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.ZhengKeChaoZhiQingKuang) : 0);

                        i.ZhengKeShiJi =
                            (zhiwhu - renshu + jieyong + chaozhi)
                                .ToString();
                    }
                }

                if (BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Count() > 0)
                {
                    foreach (BianZhiModel i in BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true))
                    {
                        i.FuKeShiJi =
                            (Convert.ToInt32(
                                BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).OrderBy(p => p.FuKeShiJi).
                                    FirstOrDefault().FuKeShiJi) +
                             BianZhiModels.Sum(
                                 p => p.FuKeJieYongQingKuang != "无" ? Convert.ToInt32(p.FuKeJieYongQingKuang) : 0) +
                             BianZhiModels.Sum(
                                 p => p.FuKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.FuKeChaoZhiQingKuang) : 0))
                                .ToString();

                        int zhiwhu = !string.IsNullOrEmpty(i.ZhengKeFeiLingDao)
                                         ? Convert.ToInt32(i.ZhengKeFeiLingDao)
                                         : 0;
                        int renshu = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                            p => !string.IsNullOrEmpty(p.fukeshiyou) ? Convert.ToInt32(p.fukeshiyou) : 0);
                        int jieyong = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                            p =>
                            p.FuKeJieYongQingKuang != "无" ? Convert.ToInt32(p.FuKeJieYongQingKuang) : 0);
                        int chaozhi = BianZhiModels.Where(p => p.ZhengKeFeiLingDaoTC == true).Sum(
                            p =>
                            p.FuKeChaoZhiQingKuang != "无" ? Convert.ToInt32(p.FuKeChaoZhiQingKuang) : 0);

                        i.ZhengKeShiJi =
                            (zhiwhu - renshu + jieyong + chaozhi)
                                .ToString();
                    }
                }
                foreach (BianZhiModel i in BianZhiModels)
                {
                    i.ZhuRenShiJi = zhurenkeyong;
                    i.FuZhuRenShiJi = fuzhurenkeyong;
                }
                if (model.ZhiWuShuXing == "非领导职务")
                {
                    if (model.ZhiWuCengCi == "乡科级正职（主任科员）" && model.ZhiWuShuXing == "非领导职务")
                    {
                        foreach (BianZhiModel i in BianZhiModels)
                        {
                            if (i.OrgID == model.AnZhiDanWei && Convert.ToInt32(!string.IsNullOrEmpty(i.ZhuRenShiJi) ? i.ZhuRenShiJi : "0") <= 0)
                            {
                                SilverlightMessageBoxLibrary.Message.ErrorMessage("岗位职数不足，请与主管部门联系！");
                                return;
                            }
                        }
                        //if (BianZhiModels.Where(p => p.OrgID == model.AnZhiDanWei && Convert.ToInt32(!string.IsNullOrEmpty(p.ZhuRenShiJi) ? p.ZhuRenShiJi : "0") <= 0).FirstOrDefault() == null)
                        //{
                        //    SilverlightMessageBoxLibrary.Message.ErrorMessage("岗位职数不足，请与主管部门联系！");
                        //    return;
                        //}
                    }
                    if (model.ZhiWuCengCi == "乡科级副职（副主任科员）" && model.ZhiWuShuXing == "非领导职务")
                    {
                        foreach (BianZhiModel i in BianZhiModels)
                        {
                            if (i.OrgID == model.AnZhiDanWei && Convert.ToInt32(!string.IsNullOrEmpty(i.FuZhuRenShiJi) ? i.FuZhuRenShiJi : "0") <= 0)
                            {
                                SilverlightMessageBoxLibrary.Message.ErrorMessage("岗位职数不足，请与主管部门联系！");
                                return;
                            }
                        }
                        //if (BianZhiModels.Where(p => p.OrgID == model.AnZhiDanWei && Convert.ToInt32(!string.IsNullOrEmpty(p.FuZhuRenShiJi) ? p.FuZhuRenShiJi : "0") > 0).FirstOrDefault() == null)
                        //{
                        //    SilverlightMessageBoxLibrary.Message.ErrorMessage("岗位职数不足，请与主管部门联系！");
                        //    return;
                        //}
                    }
                }
                //if (IsNew == true)
                //{
                //    if (!string.IsNullOrEmpty(birthday.Text)) model.Birthday = Convert.ToDateTime(birthday.Text);
                //    else
                //        model.Birthday = null;
                //    model.JiHuaID = ExameID;
                //    client.AddJuZhuanAnZhiJiHuaEmpModelAsync(model);
                //}
                //else
                //{
                //    if (!string.IsNullOrEmpty(birthday.Text)) model.Birthday = Convert.ToDateTime(birthday.Text);
                //    else
                //        model.Birthday = null;
                //    client.UpdateJuZhuanAnZhiJiHuaEmpModelAsync(model);
                //}
            }
            else
            {
                SilverlightMessageBoxLibrary.Message.ErrorMessage("该单位没有内设科室！");
                return;
            }
        }

        private void CheckBox_Checked(object sender, RoutedEventArgs e)
        {
            if (orgid1 != null) orgid1.Visibility = System.Windows.Visibility.Visible;
            if (orgid != null) orgid.Visibility = System.Windows.Visibility.Visible;
            if (Other1 != null) Other1.Visibility = System.Windows.Visibility.Collapsed;
            if (Other != null) Other.Visibility = System.Windows.Visibility.Collapsed;
            if (model != null)
            {
                model.QiTaDanWei = "";

            }
        }

        private void chkHiddenCols_Unchecked(object sender, RoutedEventArgs e)
        {
            if (orgid1 != null) orgid1.Visibility = System.Windows.Visibility.Collapsed;
            if (orgid != null) orgid.Visibility = System.Windows.Visibility.Collapsed;
            if (Other1 != null) Other1.Visibility = System.Windows.Visibility.Visible;
            if (Other != null) Other.Visibility = System.Windows.Visibility.Visible;
            if (model != null)
            {
                model.AnZhiDanWei = 0;

            }
        }

        void client_GetJuZhuanAnZhiJiHuaEmpModelCompleted(object sender, GetJuZhuanAnZhiJiHuaEmpModelCompletedEventArgs e)
        {
            if (e.Result != null && e.Result.Count > 0)
            {
                model = e.Result[0];
                if (model.AnZhiDanWei == 0) lsjl.IsChecked = false;
                else lsjl.IsChecked = true;
                this.DataContext = model;
            }
        }

        void client_UpdateJuZhuanAnZhiJiHuaEmpModelCompleted(object sender, JuZhuanAnZhiService.UpdateJuZhuanAnZhiJiHuaEmpModelCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("编辑成功！");
                this.DialogResult = true;
            }
        }

        void client_AddJuZhuanAnZhiJiHuaEmpModelCompleted(object sender, JuZhuanAnZhiService.AddJuZhuanAnZhiJiHuaEmpModelCompletedEventArgs e)
        {
            if (e.Result == true)
            {
                SilverlightMessageBoxLibrary.Message.InfoMessage("新增成功！");
                this.DialogResult = true;
            }
        }

        private void textBoxCode2_LostFocus(object sender, EventArgs e)
        {
            SetStatus(cardno.Text);
        }
        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if(model.AnZhiDanWei != 0)
            {
                //empclient.GetBianZhiDetailModelAsync(model.AnZhiDanWei.ToString(), "");
                if (IsNew == true)
                {
                    if (!string.IsNullOrEmpty(birthday.Text)) model.Birthday = Convert.ToDateTime(birthday.Text);
                    else
                        model.Birthday = null;
                    model.JiHuaID = ExameID;
                    client.AddJuZhuanAnZhiJiHuaEmpModelAsync(model);
                }
                else
                {
                    if (!string.IsNullOrEmpty(birthday.Text)) model.Birthday = Convert.ToDateTime(birthday.Text);
                    else
                        model.Birthday = null;
                    client.UpdateJuZhuanAnZhiJiHuaEmpModelAsync(model);
                }
            }
            
        }
        public void SetStatus(string idcard)
        {
            if (ValiIdCard(idcard))
            {
                model.Gender = Checks.IsMan(idcard) ? "男" : "女";
                gender.Field = "Gender";
                model.Birthday = Convert.ToDateTime(Checks.GetBirthDay(idcard).ToString());
            }
        }
        public static bool IsStringMissing(string value)
        {
            return
                String.IsNullOrEmpty(value) ||
                value.Trim() == String.Empty;
        }
        public static bool ValiIdCard(string idcard)
        {
            if (IsStringMissing(idcard)) return false;
            if (idcard == null || (idcard.Length != 15 && idcard.Length != 18))
            {
                return false;
            }

            if (idcard.Length == 18)
            {
                System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{17}(\d|x|X)$");
                System.Text.RegularExpressions.Match mc = rg.Match(idcard);
                if (!mc.Success)
                {
                    return false;
                }

                if (int.Parse(idcard.Substring(6, 4)) < 1850 || int.Parse(idcard.Substring(6, 4)) > DateTime.Now.Year + 1)
                {
                    return false; // 不允许 1850年以前的日期，以及不允许当前年＋2以后的日期

                }

                try
                {
                    DateTime.Parse(idcard.Substring(6, 4) + "-" + idcard.Substring(10, 2) + "-" + idcard.Substring(12, 2));
                }
                catch
                {
                    return false;
                }

                string idcard15 = idcard.Substring(0, 6) + idcard.Substring(8, 9);

                //if (GetLongIDCardNumber(idcard15) != idcard)
                //{
                //    return false;
                //}

            }
            else if (idcard.Length == 15)
            {
                System.Text.RegularExpressions.Regex rg = new System.Text.RegularExpressions.Regex(@"^\d{15}");
                System.Text.RegularExpressions.Match mc = rg.Match(idcard);
                if (!mc.Success)
                {
                    return false;
                }

                try
                {
                    DateTime.Parse("19" + idcard.Substring(6, 2) + "-" + idcard.Substring(8, 2) + "-" + idcard.Substring(10, 2));
                }
                catch
                {
                    return false;
                }
            }

            string[] aCity = new string[]{null,null,null,null,null,null,null,null,null,null,null,
											 "北京","天津","河北","山西","内蒙古",null,null,null,null,null,
											 "辽宁","吉林","黑龙江",null,null,null,null,null,null,null,
											 "上海","江苏","浙江","安微","福建","江西","山东",null,null,null,
											 "河南","湖北","湖南","广东","广西","海南",null,null,null,
											 "重庆","四川","贵州","云南","西藏",null,null,null,null,null,null,
											 "陕西","甘肃","青海","宁夏","新疆",null,null,null,null,null,
											 "台湾",null,null,null,null,null,null,null,null,null,
											 "香港","澳门",null,null,null,null,null,null,null,null,"国外"};
            if (aCity[int.Parse(idcard.Substring(0, 2))] == null)
            {
                return false;
            }

            return true;
        }
    }
}
